package org.nowcoder.huawei.c200;

import java.util.Scanner;

/**
 * 28：寻找最优的路测线路
 */

public class HC028 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int R = scanner.nextInt();
        int C = scanner.nextInt();
        int[][] Cov = new int[R][C];
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                Cov[i][j] = scanner.nextInt();
            }
        }
        int bestRouteScore = bestRouteScore(R, C, Cov);
        System.out.println(bestRouteScore);
    }


    private static boolean solve(int[][] Cov, int R, int C, int mid, boolean[][] visited, int x, int y) {
        // DFS 辅助函数，用于检查是否存在一条至少为 mid 信号质量的路径
        // 首先检查当前位置是否合法
        if (x < 0 || x >= R || y < 0 || y >= C || visited[x][y] || Cov[x][y] < mid) {
            return false;
        }

        // 到达终点
        if (x == R - 1 && y == C - 1) {
            return true;
        }

        // 标记当前栅格为已访问
        visited[x][y] = true;

        // 探索四个方向
        if (solve(Cov, R, C, mid, visited, x + 1, y) ||
                solve(Cov, R, C, mid, visited, x - 1, y) ||
                solve(Cov, R, C, mid, visited, x, y + 1) ||
                solve(Cov, R, C, mid, visited, x, y - 1)) {
            return true;
        }

        // 回溯
        visited[x][y] = false;
        return false;
    }

    private static int bestRouteScore(int R, int C, int[][] Cov) {
        int left = 0;
        int right = 0;

        // 找到信号质量的可能范围
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                right = Math.max(right, Cov[i][j]);
            }
        }

        // 使用二分查找来确定最大最小值
        while (left < right) {
            int mid = (left + right + 1) / 2; // 向上取整避免死循环
            boolean[][] visited = new boolean[R][C]; // 记录访问状态

            if (solve(Cov, R, C, mid, visited, 0, 0)) {
                left = mid; // 存在这样的路径，尝试更大的值
            } else {
                right = mid - 1; // 不存在，降低标准
            }
        }

        return left; // left 和 right 相遇，即为所求
    }
}

